/**
 * 
 */
package br.com.ac.fatureweb.view;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import javax.faces.event.ActionEvent;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;

import br.com.ac.fatureweb.enums.EnumStatusCarga;
import br.com.ac.fatureweb.jf.model.exporter.Ficha;
import br.com.ac.fatureweb.model.Carga;
import br.com.ac.fatureweb.service.NgcExportacaoBean;
import br.com.ac.fatureweb.service.NgcRoteiroBean;
import br.com.ac.fatureweb.utilitary.FacesUtils;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;

/**
 * @author aldivone
 *
 */
@Named
@ViewScoped
public class ExportacaoBean implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 944076850947534736L;

	@Inject
	private NgcRoteiroBean ngcRoteiroBean;

	@Inject
	private NgcExportacaoBean ngcExportacaoBean;

	private Carga carga;

	public void exportarSaae(ActionEvent event) {
		try {
			List<Ficha> lstFicha = ngcExportacaoBean
					.getLstDadosExportar(getCarga().getId());

			final JsonArray array = new JsonArray();
			for (final Object ficha : lstFicha) {
				JsonElement fichaJson = new Gson().toJsonTree(ficha);

				array.add(fichaJson);
			}

			HttpURLConnection httpcon = (HttpURLConnection) ((new URL(
					"http://201.31.9.244:8081/jf/service/retorno")
					.openConnection()));
			httpcon.setDoOutput(true);
			httpcon.setDoInput(true);
			httpcon.setRequestProperty("Content-Type", "application/json");
			httpcon.setRequestProperty("Accept", "application/json");
			httpcon.setRequestMethod("POST");
			httpcon.setReadTimeout(10000);
			httpcon.setConnectTimeout(15000);
			httpcon.connect();

			byte[] outputBytes = array.toString().getBytes("UTF-8");

			OutputStream os = httpcon.getOutputStream();

			os.write(outputBytes);

			os.flush();

			os.close();

			BufferedReader br = new BufferedReader(new InputStreamReader(
					httpcon.getInputStream(), "UTF-8"));

			StringBuffer dadosUrl = new StringBuffer();
			String dado = "";
			while (null != ((dado = br.readLine()))) {
				dadosUrl.append(dado);
			}
			br.close();

			FacesUtils.addMessageInformation(dadosUrl.toString());

			// TODO colocar a carga como enviado para o SAAE.

		} catch (Exception ex) {
			ex.printStackTrace();
			FacesUtils.addMessageError("Erro no "
					+ "processamento da carga de retorno ao SAAE.");
		}
	}

	public List<Carga> getLstCarga() {
		return ngcRoteiroBean.getLstCarga(EnumStatusCarga.FINALIZADO);
	}

	/**
	 * @return the carga
	 */
	public Carga getCarga() {
		return carga;
	}

	/**
	 * @param carga
	 *            the carga to set
	 */
	public void setCarga(Carga carga) {
		this.carga = carga;
	}

}
